#include<bits/stdc++.h>
using namespace std;

class Solution
{
private:
    /* data */
public:
    int res =0;
    int islandPerimeter(vector<vector<int>>& grid){
        vector<vector<int>> dire ={{-1,0},{1,0},{0,-1},{0,1}};
        for(int i=0;i<grid.size();++i){
            for(int j=0;j<grid[0].size();++j){
                if(grid[i][j]==1){
                    dfs(grid,dire,i,j);
                }
            }
        }
        return res;
    }

    void dfs(vector<vector<int>>& grid,vector<vector<int>>& dire,int x,int y){
        if(x<0 || x>= grid.size() || y<0 || y>=grid[0].size() || grid[x][y]==0){
            ++res;
            return;
        }
        if(grid[x][y]==2){
            return;
        }
        if(grid[x][y]==1){
            grid[x][y]=2;
        }
        for(int i=0;i<4;++i){
            dfs(grid,dire,x+dire[i][0],y+dire[i][1]);
        }
    }
};



int main(int argc, char const *argv[])
{
    /* code */
    // vector<vector<int>> grid={{1,0}};
    vector<vector<int>> grid={{0,1,0,0},{1,1,1,0},{0,1,0,0},{1,1,0,0}};
    Solution s;
    s.islandPerimeter(grid);
    cout<<s.res<<endl;
    return 0;
}
